package com.shxs.controller;
import com.shxs.LLMConnect.LLMTools.LLMSplitTool;
import com.shxs.LLMConnect.chatGLM.ChatGLMConnector;
import com.shxs.common.BaseResponse;
import com.shxs.model.entity.Dialog;
import com.shxs.model.entity.MINIMAX.MINIMAXRequest;
import com.shxs.model.entity.NovelTable;
import com.shxs.model.entity.User;


import cn.hutool.http.HttpResponse;
import com.shxs.model.entity.VoiceGenerateRequest;
import com.shxs.service.INovelTableService;
import com.shxs.service.MINIMAXService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 语音生成接口
 *
 */
@RestController
@RequestMapping("/voice")
@Slf4j
public class VoiceGenerateController {
    @Resource
    private MINIMAXService minimaxService;

    /**
     * 生成并返回语音
     *
     * @param voiceGenerateRequest
     * @return
     */
    @Autowired
    private INovelTableService novelTableService;

    @Value("${shxs.path}")
    private String basePath;
    static int index=0;
    @PostMapping("/generate")
    public BaseResponse<HttpResponse> voiceGenerate(@RequestBody VoiceGenerateRequest voiceGenerateRequest) {
        String text = voiceGenerateRequest.getText();
        String glm_api_key = voiceGenerateRequest.getGlm_api_key();

        LLMSplitTool llmSplitTool = new LLMSplitTool(new ChatGLMConnector(glm_api_key).temperature(0.5f));
        //todo 可能需要开一个线程异步处理
        //处理文本
        String targetText = LLMSplitTool.create(text);
        //获得每句话的角色
        String roles_string ;
        List<Dialog> dialogs;
        //List<Dialog> dialogs = LLMSplitTool.getDialogs(targetText, roles_string);
        Map<String,String> rolesVoiceMap;
        if(targetText.length()==text.length()){
            dialogs = new ArrayList<>();
            dialogs.add(new Dialog(text, "旁白", "男性主持人"));
        }
        else {
            NovelTable novelTable = novelTableService.selectNovelTableByNovelId(voiceGenerateRequest.getNovelId());
            if (novelTable != null) {
                rolesVoiceMap = novelTable.getVoiceRoleTableListAsMap();
                roles_string = llmSplitTool.doSplitWithHistory(targetText, rolesVoiceMap);
                rolesVoiceMap = LLMSplitTool.getVoiceRoles(roles_string, rolesVoiceMap);
                novelTable.setVoiceRoleTableListByMap(rolesVoiceMap);
                novelTableService.updateNovelTable(novelTable);
            } else {
                novelTable = new NovelTable();
                roles_string = llmSplitTool.doSplitWithHistory(targetText, null);
                rolesVoiceMap = LLMSplitTool.getVoiceRoles(roles_string, null);
                novelTable.setNovelName(voiceGenerateRequest.getNovelName());


                //novelTable.setNovelId();//此处需要生成一个novelid


                novelTable.setVoiceRoleTableListByMap(rolesVoiceMap);
                novelTable.setUserId(voiceGenerateRequest.getUser().getId());
                novelTableService.insertNovelTable(novelTable);
            }

            dialogs = LLMSplitTool.refacterDialogs(targetText, roles_string, rolesVoiceMap);
        }


        try {
            // 将输入流写入到文件中
            FileOutputStream fileOutputStream = new FileOutputStream(basePath + index + ".mp3");
            index++;
            byte[] buffer = new byte[4096];
            int bytesRead;
            for (int i = 0; i < dialogs.size(); i++) {
                System.out.println("音频已生成：" + i );
                Dialog dialog = dialogs.get(i);
                System.out.println(dialog);
                MINIMAXRequest minimaxRequest = minimaxService.getMINIMAXRequest(dialog, voiceGenerateRequest);
                System.out.println(minimaxRequest);
                InputStream inputStream= minimaxService.doRequest(minimaxRequest, i);

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }
            }
            fileOutputStream.close();
            System.out.println("音频已保存为：" + index + ".mp3");
        }
        catch (Exception e) {
            System.out.println(e.toString());
        }
        return null;
    }
}
